package com.powernode.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 内容:
 * 作者: cy
 */
@Configuration
public class AuthRouteConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 使用代码方式的路由去存储token
     *
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator authRoute(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("auth-route-id", r -> r.path("/oauth/token")
                        .filters(f -> f.modifyResponseBody(String.class, String.class, (exchange, s) -> {
                            JSONObject jsonObject = JSON.parseObject(s);
                            // 拿到token
                            String accessToken = jsonObject.getString("access_token");
                            if (StringUtils.hasText(accessToken)) {
                                // 拿到时间
                                Long expiresIn = jsonObject.getLong("expires_in");
                                // 存储redis
                                redisTemplate.opsForValue().set(GatewayConstant.AUTH_TOKEN_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
                            }
                            return Mono.just(s);
                        }))
                        .uri("lb://auth-server"))
                .build();

    }

}
